package com.lucy.management.service;

import com.lucy.management.config.exception.ExceptionCast;
import com.lucy.management.config.exception.ExceptionCatch;
import com.lucy.management.dao.CmsSiteRepository;
import com.lucy.management.domain.CmsSite;
import com.lucy.management.utils.AjaxResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class CmsSiteService {
    @Autowired
    CmsSiteRepository cmsSiteRepository;

    public AjaxResult getSiteList(int page, int size, Map map) {
        if (page <= 0) page = 1;
        if (size <= 0) size = 10;
        page = page - 1;
        Pageable pageable = PageRequest.of(page, size);
        //加上模糊查询不行啊

/*
        String siteId = (String) map.get("siteId");
*/
        String siteName = (String) map.get("siteName");
        CmsSite cmsSite = new CmsSite();
        /*if (StringUtils.isNotEmpty(siteId)) {
            cmsSite.setSiteId(siteId);
        }*/
        if (StringUtils.isNotEmpty(siteName)) {
            cmsSite.setSiteName(siteName);
        }


        ExampleMatcher matching = ExampleMatcher.matching();
        matching = matching.withMatcher("siteName", ExampleMatcher.GenericPropertyMatchers.contains());

        Example<CmsSite> example = Example.of(cmsSite, matching);
        Page<CmsSite> all = cmsSiteRepository.findAll(pageable);
        return AjaxResult.success(all);
    }

    public AjaxResult getSite(String id) {

        Optional<CmsSite> optional = cmsSiteRepository.findById(id);
        if (!optional.isPresent()) {
            ExceptionCast.cast("未查询到站点");
        }
        return AjaxResult.success(optional.get());
    }

    public AjaxResult save(CmsSite cmsSite) {
        String siteId = cmsSite.getSiteId();
        cmsSite.setSiteCreateTime(new Date());
        if (StringUtils.isNotEmpty(siteId)) {
            //更新
            Optional<CmsSite> optional = cmsSiteRepository.findById(siteId);
            if (!optional.isPresent()) {
                ExceptionCast.cast("未查询到站点");
            }
            CmsSite saveModel = optional.get();
            BeanUtils.copyProperties(cmsSite, saveModel);
            cmsSiteRepository.save(cmsSite);
        } else {
            //新增
            cmsSite.setSiteId(null);
            cmsSiteRepository.save(cmsSite);
        }
        return AjaxResult.success("操作成功", null);
    }

    @Transactional
    public AjaxResult delete(List<String> ids) {
        for (String id : ids) {
            cmsSiteRepository.deleteById(id);
        }
        return AjaxResult.success("操作成功", null);
    }
}
